<template>

  <div>
    <van-nav-bar title="积分商城" left-text="返回"
                 left-arrow
                 @click-left="back"/>
    <!-- 积分商城标题 -->

    <!-- 用户积分总数 -->
    <p class="points-total">您的积分总计：{{ totalPointss }}</p>

    <!-- 商品列表 -->
    <div class="product-list">
      <div v-for="(product, index) in products" :key="index" class="product-item">
        <!-- 商品图片 -->
        <img :src="product.image" alt="Product Image" class="product-image"/>

        <!-- 商品名称和描述 -->
        <div class="product-info">
          <h2 class="product-name">{{ product.name }}</h2>
          <p class="product-description">{{ product.description }}</p>
        </div>

        <!-- 商品价格和购买按钮 -->
        <div class="product-action">
          <p class="product-price">{{ product.price }}积分</p>
          <van-button type="primary" block round @click="buyShopping(product.id,product.price)">购买</van-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {defineComponent, ref, onMounted, computed} from "vue";
import axios from "axios";
import {getProducts, getConsumption, getUserPoints} from "@/apis/api.js"
import {showConfirmDialog, showDialog} from "vant"
export default defineComponent({
  name: "PointMall",
  props: {
    totalPoints: Number,
  },
  setup(props) {
    const products = ref([]);
    const loading = ref(false);
    const totalPointss = ref(0)

    // 后端接口URL
    const apiUrl = "localhost:8081/api/products";

    const getUserPointsFunc = async () => {
      const res = await getUserPoints()
      totalPointss.value = res.data.growths
    }

    // 获取商品列表
    const fetchProducts = async () => {
      console.log(1111111111111111, apiUrl)
      try {
        const response = await axios.get(apiUrl);
        products.value = response.data;
        loading.value = false;
      } catch (error) {
        console.error("Error fetching products:", error);
      }
    };

    const initListData = async () => {
      if (loading.value) return
      loading.value = true
      const result = await getProducts()
      products.value = result;
      loading.value = false;
    }

    const buyShopping = async (id,price) => {
      showConfirmDialog({
        title: '提示',
        message: '确认购买吗？',

      })
          .then(async () => {
            try{
              // on confirm
              const res = await getConsumption({id,price})
              console.log('34333333333333',res)
              if(res.code===200) {
                // 购买成功初始化页面
                initPage()
                showDialog({
                  title: '提示',
                  message: '购买成功！',
                });
              }else if(res.code===500){
                showDialog({
                  title: '提示',
                  message: '购买失败，积分不足！',
                });
              }

              // 买哪个会500  我写的后端是当积分少于商品的积分的时候会return一个500

            }catch (e) {
              console.log(e)
            }

          })
          .catch(() => {
            // on cancel
          });
    }







    // 处理购买操作
    const handlePurchase = async (productId) => {
      console.log("购买商品ID：", productId)
      return
      try {

        await axios.post(`localhost:8081/api/purchase/${productId}`, {productId});
        alert("购买成功！");
      } catch (error) {
        console.error("Error purchasing product:", error);
        alert("购买失败，请稍后再试。");
      }
    };
    const back = () => {
      history.back();
    };

    const initPage = () => {
      initListData()
      getUserPointsFunc()
    }

    // 初始化
    onMounted(() => {
      initPage()
      // fetchProducts()
    });

    return {
      back,
      products,
      handlePurchase,
      buyShopping,
      totalPointss
    };
  },
});

</script>

<style scoped>
.title {
  text-align: center;
  margin-bottom: 20px;
}
* {
  line-height: 1.2;
}

.product-list {
  padding: 0 24px;
}
.points-total {
  font-size: 18px;
  color: #999;
  text-align: center;
  margin-bottom: 20px;
}

.product-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  gap: 20px;
}

.product-item {
  width: calc(50% - 11%);
  background-color: #fff;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.product-image {
  max-width: 100%;
  width: auto;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 10px;
}

.product-info {
  margin-bottom: 10px;
}
.product-description {
  text-overflow: ellipsis;
  overflow: hidden;
  //white-space: nowrap;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;

}

.product-name {
  font-size: 18px;
  margin-bottom: 5px;
}

.product-description {
  color: #999;
  line-height: 1.5;
}

.product-price {
  font-size: 16px;
  color: #f60;
  margin-bottom: 10px;
}
</style>
